package com.wjk.easy.data;

import com.wjk.easy.data.model.LoggedInUser;
import com.wjk.easy.db.LastUserBean;
import com.wjk.easy.db.UserBean;
import com.wjk.easy.utils.CommonUtil;
import com.wjk.easy.utils.D;

import org.litepal.LitePal;
import java.io.IOException;
import java.util.List;

/**
 * Class that handles authentication w/ login credentials and retrieves user information.
 */
public class LoginDataSource {

    public Result<LastUserBean> login(String username, String password) {

        try {
            UserBean tempUser = D.queryUserByName(username);
            if(tempUser!=null){//用户存在;
                if(tempUser.getPassword().equals(CommonUtil.getStringMD5(password))){
                    LastUserBean lastUserBean = new LastUserBean(tempUser.getUsername(),tempUser.getId());
                    //保存当前用户登录痕迹
                    LitePal.deleteAll(LastUserBean.class);
                    lastUserBean.save();
                    return new Result.Success<>(lastUserBean);
                }else{
                    return new Result.Error(new Exception("密码不正确"));
                }
            }else{
                return new Result.Error(new Exception("用户名不存在"));
            }
        } catch (Exception e) {
            return new Result.Error(new IOException("登录过程出错:", e));
        }
    }
    public Result<LastUserBean> regist(String username, String password) {
        try {
            UserBean userBean = D.queryUserByName(username);
            if(userBean!=null){//用户已存在
                return new Result.Error(new Exception("用户名已存在"));
            }else{
                UserBean tempUser = new UserBean(username,CommonUtil.getStringMD5(password));
                tempUser.save();
                LastUserBean lastUserBean = new LastUserBean(tempUser.getUsername(),tempUser.getId());
                //保存当前用户登录痕迹
                LitePal.deleteAll(LastUserBean.class);
                lastUserBean.save();
                return new Result.Success<>(lastUserBean);
            }
        } catch (Exception e) {
            return new Result.Error(new IOException("登录过程出错:", e));
        }
    }
    public void logout() {
        LitePal.deleteAll(LastUserBean.class);
    }
    public Result<LastUserBean> resetPwd(String username, String password) {
        try {
            UserBean userBean = D.queryUserByName(username);
            if(userBean!=null){
                userBean.setPassword(CommonUtil.getStringMD5(password));
                userBean.save();
                LastUserBean lastUserBean = new LastUserBean(userBean.getUsername(),userBean.getId());
                return new Result.Success<>(lastUserBean);
            }else{//用户不存在
                return new Result.Error(new Exception("您输入的用户名不存在"));
            }
        } catch (Exception e) {
            return new Result.Error(new IOException("修改密码出错:", e));
        }
    }
}
